package com.fand.manager.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fand.stater.model.SysUserDetailDTO;
import com.fand.stater.context.UserInfoThreadLocal;
import com.fand.common.exception.BusinessException;
import com.fand.common.util.PageResult;
import com.fand.manager.entity.SysMenu;
import com.fand.manager.mapper.SysMenuMapper;
import com.fand.manager.model.menu.IndexMenuDTO;
import com.fand.manager.model.menu.SysMenuDeleteDTO;
import com.fand.manager.model.menu.SysMenuPostDTO;
import com.fand.manager.model.menu.SysMenuReturnDTO;
import com.fand.manager.model.menu.SysPMenuReturnDTO;
import com.fand.manager.service.ISysMenuService;
import com.fand.manager.util.MenuTreeUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 菜单 服务实现类
 * </p>
 *
 * @author javaboy
 * @since 2021-06-07
 */
@Service
@RefreshScope
public class SysMenuServiceImpl implements ISysMenuService {

    @Value("${system.root.usercode:admin}")
    private String rootUserCode;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Transactional
    @Override
    public SysMenuReturnDTO saveMenu(SysMenuPostDTO sysMenuPostDTO) {
        if (Objects.isNull(sysMenuPostDTO) || Objects.isNull(sysMenuPostDTO.getName())) {
            throw new BusinessException("数据不完整");
        }
        SysMenuReturnDTO sysMenuReturnDTO = SysMenuReturnDTO.builder().build();
        SysMenu sysMenu = SysMenu.builder().build();
        BeanUtil.copyProperties(sysMenuPostDTO, sysMenu);
        int rows = sysMenuMapper.insert(sysMenu);
        if (rows < 1) {
            return sysMenuReturnDTO;
        }
        BeanUtil.copyProperties(sysMenu, sysMenuReturnDTO);
        return sysMenuReturnDTO;
    }

    @Override
    public PageResult<List<SysMenuReturnDTO>> listMenus() {
        List<SysMenu> sysMenus = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
        if (CollUtil.isEmpty(sysMenus)) {
            return new PageResult<>();
        }
        List<SysMenuReturnDTO> sysMenuReturnDTOS = sysMenus.stream().map(sysMenu -> {
            SysMenuReturnDTO sysMenuReturnDTO = SysMenuReturnDTO.builder().build();
            BeanUtil.copyProperties(sysMenu, sysMenuReturnDTO);
            return sysMenuReturnDTO;
        }).collect(Collectors.toList());

        return new PageResult<>(sysMenuReturnDTOS.size(), sysMenuReturnDTOS);
    }

    @Transactional
    @Override
    public Boolean deleteByIds(List<Long> menuIds) {
        if (CollUtil.isEmpty(menuIds)) {
            throw new BusinessException("请选中要删除的菜单");
        }
        int rows = sysMenuMapper.deleteBatchIds(menuIds);
        if (rows < 1) {
            throw new BusinessException("删除菜单失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public SysMenuReturnDTO findMenu(Long id) {
        if (Objects.isNull(id) || id < 1) {
            throw new BusinessException("请选中菜单");
        }
        SysMenu sysMenu = sysMenuMapper.selectById(id);
        SysMenuReturnDTO sysMenuReturnDTO = SysMenuReturnDTO.builder().build();
        if(!sysMenu.getPid().equals(-1L)){
            String name = sysMenuMapper.selectById(sysMenu.getPid()).getName();
            sysMenuReturnDTO.setName(name);
        }
        BeanUtil.copyProperties(sysMenu, sysMenuReturnDTO);
        return sysMenuReturnDTO;

    }

    @Override
    public SysPMenuReturnDTO findPMenu(Long pid) {
        if (Objects.isNull(pid) || pid < 1) {
            throw new BusinessException("请选中菜单");
        }
        SysMenu sysMenu = sysMenuMapper.selectById(pid);
        if (Objects.nonNull(sysMenu)) {
            return SysPMenuReturnDTO.builder().pid(sysMenu.getId()).pname(sysMenu.getName()).build();
        }
        return SysPMenuReturnDTO.builder().build();
    }

    @Transactional
    @Override
    public Boolean deleteById(SysMenuDeleteDTO sysMenuDeleteDTO) {
        if(Objects.isNull(sysMenuDeleteDTO)||Objects.isNull(sysMenuDeleteDTO.getId())){
            throw new BusinessException("参数为空");
        }
        sysMenuMapper.delete(new QueryWrapper<SysMenu>().eq("pid",sysMenuDeleteDTO.getId()));
        sysMenuMapper.deleteById(sysMenuDeleteDTO.getId());
        return Boolean.TRUE;
    }

    @Override
    public List<SysMenuReturnDTO> findMenuByPid(Long pid) {
        if(Objects.isNull(pid)|| pid < 1){
            throw new BusinessException("参数不合法");
        }

        List<SysMenu> sysMenus = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("pid", pid));
        if(CollUtil.isNotEmpty(sysMenus)){
            List<SysMenuReturnDTO> sysMenuReturnDTOList = sysMenus.stream().map(sysMenu -> {
                SysMenuReturnDTO sysMenuReturnDTO = SysMenuReturnDTO.builder().build();
                BeanUtil.copyProperties(sysMenu, sysMenuReturnDTO);
                return sysMenuReturnDTO;
            }).collect(Collectors.toList());
            return sysMenuReturnDTOList;
        }
        return CollUtil.newArrayList();
    }

    @Override
    public IndexMenuDTO indexMenu() {
        IndexMenuDTO indexMenuDTO = IndexMenuDTO.builder().build();
        SysUserDetailDTO sysUserDetailDTO = UserInfoThreadLocal.get();
        if(Objects.nonNull(sysUserDetailDTO)){
            Long userId = sysUserDetailDTO.getId();
            indexMenuDTO.setHomeInfo(IndexMenuDTO.HomeInfoBean.builder().title("首页").href("/welcome").build());
            indexMenuDTO.setLogoInfo(IndexMenuDTO.LogoInfoBean.builder().title("寻 物").image("http://117.80.114.220:81/static/images/logo.png").href("/").build());
            //组装菜单
            List<SysMenu> sysMenuList = null;
            if(rootUserCode.equals(sysUserDetailDTO.getUsername())){
                sysMenuList = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
            }else{
                sysMenuList = sysMenuMapper.listMenuByUserCode(userId);
            }
            if(CollUtil.isNotEmpty(sysMenuList)){
                sysMenuList = sysMenuList.stream().filter(sysMenu -> sysMenu.getType() != 1).collect(Collectors.toList());
                List<IndexMenuDTO.MenuInfoBean> menuInfoBeans = MenuTreeUtil.menu2IndexMenu(sysMenuList);
                indexMenuDTO.setMenuInfo(menuInfoBeans);
            }
        }
        return indexMenuDTO;
    }

    @Transactional
    @Override
    public Boolean updateMenu(SysMenuPostDTO sysMenuPostDTO) {
        if (Objects.isNull(sysMenuPostDTO) || Objects.isNull(sysMenuPostDTO.getId()) || sysMenuPostDTO.getId() < 1) {
            throw new BusinessException("数据不完整");
        }
        SysMenu sysMenu = SysMenu.builder().build();
        BeanUtil.copyProperties(sysMenuPostDTO, sysMenu);
        int row = sysMenuMapper.updateById(sysMenu);
        if (row < 0) {
            throw new BusinessException("修改数据失败");
        }
        return Boolean.TRUE;
    }
}
